<!--  -->
<template>
  <div>
    <div class="  text-slate-400 ">【各类电影占比】</div>
    <div ref="target" class="w-full h-full"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import * as echarts from "echarts";

const props = defineProps({
  data: Array,
});
// console.log("props:", props);
let chart = null;
const target = ref(null);
onMounted(() => {
  chart = echarts.init(target.value);
  ChartInit(); // 将 chart 传递给 ChartInit 函数
});
const ChartInit = () => {
  if (!props.data || props.data.length === 0) {
    console.log("No data to display");
    return;
  }

  const directorCount = props.data.reduce((acc, item) => {
    if (item !== undefined && item !== null) {
      acc[item] = (acc[item] || 0) + 1;
    }
    return acc;
  }, {});
  // 提取统计结果
  const yAxisData = Object.keys(directorCount).sort((a , b) => directorCount[b] - directorCount[a])
  const seriesData = yAxisData.map((item) => directorCount[item]);
  // console.log("yAxisData:", yAxisData);
  // console.log("seriesData:", seriesData);
  const option = {
    tooltip: {
      trigger: "item",
    },
    // legend: {
    //   top: "5%",
    //   left: "center",
    //   textStyle : {
    //     color : "#fff",
    //   }
    // },
    series: [
      {
        name: "类型",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: "center",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 26,
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: yAxisData.map((letter ,index) => ({
          value : seriesData[index],
          name:letter,
        }))
      },
    ],
  };

  // console.log("option:", option); // 检查 option 对象
  try {
    chart.setOption(option);
  } catch (error) {
    console.error("Error setting option:", error);
  }
};

watch(() => props.data, ChartInit);
</script>

<style lang="scss" scoped></style>
